import React from 'react';
import { connect } from 'dva';
import { DoubleRightOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Upload, Modal, Progress, message } from 'antd';
import router from 'umi/router';
import downloadFile from '@/utils/utils';

@connect()
@Form.create()
class FileUpload extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
    };
  }

  // 上传文件
  uploadFile = () => {
    const { uploadFile } = this.props;
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file);
    });
    uploadFile(formData);
  };

  render() {
    const {
      currentStep,
      downloadTempInfo,
      uploading,
      progressTitle = '上传进度条',
      progressPercent,
      progressVisible,
      handleModalVisible,
      setCurrentstep,
      isExact,
      maskClosable = false,
      preStep = () => {
        if (currentStep) {
          setCurrentstep(currentStep - 1);
        } else {
          router.goBack();
        }
      },
      limitSize = 0, // 默认不限制，单位M
    } = this.props;
    const { fileList } = this.state;
    const props = {
      beforeUpload: file => {
        if (limitSize) {
          const isLimitsize = file.size / 1024 / 1024 < limitSize; // 文件限制5M
          if (!isLimitsize) {
            return message.warning(
              `为了保证系统能够快速响应，上传文件大小不能超过${limitSize}M，如数据量太多，建议拆分后分批上传！`
            );
          }
        }
        const fileTye = [
          // 默认限制类型，excel,传空数组表示不限制类型,或者传文件其他类型
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'xlsx',
          'xls',
        ];
        const isType = !file.type ? file.name && file.name.split('.')[1] : file.type;
        const isExcel = fileTye.indexOf(isType) > -1;
        if (!isExcel) {
          return message.warning('文件格式错误，只能上传excel表格格式!');
        }
        if (fileList.length === 1) {
          return message.warning('建议一次只能上传一个文件');
        }
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
    };
    return (
      <Form layout="horizontal">
        {isExact ? <this.props.isExact /> : null}
        <div
          style={{
            width: 480,
            height: 200,
            margin: '0 auto',
            marginTop: 50,
            textAlign: 'center',
          }}
        >
          <Button
            icon={<DownloadOutlined />}
            onClick={() =>
              downloadFile(downloadTempInfo.params, downloadTempInfo.url, downloadTempInfo.type)
            }
            style={{ zIndex: 88 }}
          >
            下载模板
          </Button>
          <DoubleRightOutlined
            style={{
              display: 'block',
              margin: '20px auto',
              fontSize: 30,
              transform: 'rotate(90deg)',
              zIndex: 1,
            }} />
          <Upload {...props} sty>
            <Button icon={<UploadOutlined />} style={{ zIndex: 88 }}>
              上传
            </Button>
          </Upload>
        </div>
        <Modal
          title={progressTitle}
          footer={null}
          closable={false}
          maskClosable={maskClosable}
          visible={progressVisible}
          onCancel={() => handleModalVisible()}
        >
          <div style={{ textAlign: 'center' }}>
            <Progress percent={progressPercent} format={percent => `${percent}%`} />
          </div>
        </Modal>
        <div style={{ textAlign: 'center', marginTop: 100 }}>
          <Button onClick={() => preStep()} style={{ marginRight: 8 }}>
            {currentStep ? '上一步' : '返回'}
          </Button>
          <Button
            type="primary"
            onClick={this.uploadFile}
            disabled={fileList.length === 0}
            loading={uploading}
          >
            提交
          </Button>
        </div>
      </Form>
    );
  }
}

export default FileUpload;
